package com.study.module.datasource.config;

import com.study.module.datasource.enums.DataSourceType;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableConfigurationProperties(DataSourceConfig.class)
public class DynamicDataSourceConfig {

    @Bean
    public DataSourceRouter dynamicDataSource(DataSourceConfig config) {
        Map<String, DataSourceProperties> map = config.getDatasource();
        DataSourceRouter dataSourceRouter = new DataSourceRouter();
        //设置默认数据源
        DataSourceProperties properties = map.get(DataSourceType.MASTER.getCode());
        dataSourceRouter.setDefaultTargetDataSource(DataSourceFactory.build(properties));
        //设置数据源集合
        Map<Object, Object> targetDataSources = new HashMap<>(map.size());
        map.forEach((k, v) -> targetDataSources.put(k, DataSourceFactory.build(v)));
        dataSourceRouter.setTargetDataSources(targetDataSources);
        return dataSourceRouter;
    }

}